package es.udc.emarketapp.emarket.model.categoryFacade.actions;

import es.udc.emarketapp.emarket.model.category.dao.SQLCategoryDAO;
import es.udc.emarketapp.emarket.model.category.dao.SQLCategoryDAOFactory;
import es.udc.emarketapp.emarket.model.category.vo.CategoryVO;
import es.udc.emarketapp.emarket.model.categoryFacade.vo.CategoryChunkVO;
import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import java.util.List;

public class GetSonsCategoryAction implements NonTransactionalPlainAction {

    private Long catPadre;
    private int startIndex;
    private int count;

    public GetSonsCategoryAction(Long catPadre, int startIndex, int count) {
        this.catPadre = catPadre;
        this.startIndex = startIndex;
        this.count = count;
    }

    public Object execute(Connection connection)
            throws InternalErrorException {

        SQLCategoryDAO categoryDAO = SQLCategoryDAOFactory.getDAO();
        List<CategoryVO> categoryVOs = categoryDAO.getSons(connection,
                catPadre, startIndex, count + 1);

        boolean existMoreCategories = categoryVOs.size() == (count + 1);

        if (existMoreCategories) {
            categoryVOs.remove(categoryVOs.size() - 1);
        }

        return new CategoryChunkVO(categoryVOs, existMoreCategories);

    }
}
